<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    const _arr = [
        {
            id: 1,
            children: [
                {
                    id: 2,
                    children: [
                        {
                            id: 3,
                            children: [
                                {
                                    id: 4
                                },
                                {
                                    id: 5
                                },
                                {
                                    id: 6
                                },
                                {
                                    id: 7
                                },
                                {
                                    id: 8
                                },
                            ]
                        }
                    ]
                }
            ]
        },
        {
            id: 11,
            children: [
                {
                    id: 21,
                    children: [
                        {
                            id: 31
                        }
                    ]
                }
            ]
        },
    ]

    const _index = [0, 0]
    const _index2 = [0, 0, 0]

    // 思路-1
    // function getId(arr, index, currentIndex) {
    //     if ((currentIndex < index.length - 1) && arr[index[currentIndex]].children && arr[index[currentIndex]].children.length) {
    //         return getId(arr[index[currentIndex]].children, index, ++currentIndex)
    //     } else {
    //         return arr[index[currentIndex]].id
    //     }
    // }

    // 思路-2
    function getId(arr, index) {
        const item = arr[index[0]]
        if (item.children && item.children.length && index.length > 1) {
            return getId(item.children, index.splice(1))
        } else {
            return item.id
        }
    }

    console.log(getId(_arr, _index)); // 2
    console.log(getId(_arr, _index2)); // 8
</script>
</body>
</html>
